﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint.Administration;
using Trentacular.SharePoint.Deployment.Model;
using Trentacular.SharePoint.Deployment.Util;

namespace Trentacular.SharePoint.Deployment.Data.Proxy
{
    public class SolutionDeployedWebApplicationsLazyInitializer : BaseDomainListLazyInitializer<Solution, WebApplication>
    {
        protected override object InitializeTarget()
        {
            var spFarm = SPFarm.Local;
            var spSolution = spFarm.Solutions[Owner.Id];

            var deployedApplications = spSolution.DeploymentState
                .Is(
                    SPSolutionDeploymentState.WebApplicationDeployed,
                    SPSolutionDeploymentState.GlobalAndWebApplicationDeployed
                    ) ?
                spSolution.DeployedWebApplications
                    .Select(wa => wa.Id)
                    .ToList() :
                new List<Guid>();

            return Owner.Farm.WebApplications
                .Where(wa => Owner.Deployed &&
                        (
                            Owner.DeploymentState == SPSolutionDeploymentState.GlobalDeployed ||
                            deployedApplications.Contains(wa.Id)
                        )
                    )
                .ToVirtualList();
        }
    }
}
